package net.action;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import net.domain.User;
import net.service.UserService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by zyh on 2017/2/27.
 */
@Controller
@Scope("prototype")
public class UserAciton extends ActionSupport implements ModelDriven<User>{
    private Log log = LogFactory.getLog(this.getClass());
    private String message;


    private User model = new User();

    @Resource
    private UserService userService;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

/*    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }*/

    /*注册界面*/
    public String registerUi() {
        return "registerUi";
    }

    public String loginUi(){return "loginUi";}

    public String register() {
       User user = userService.findByUsernamePassword(model.getUsername(),model.getPassword());
        System.out.println("name:" + model.getUsername());

        if (user==null) {

//            message = "注册失败，用户已存在";
            this.addActionError("注册失败，用户已存在");
            return "registerFail";
        } else {
//            message = "注册成功";
            this.addActionMessage("注册成功");
            return "registerSuccess";

        }
    }

    public String login() {
        User user = userService.loginByUsernamePassword(model.getUsername(),model.getPassword());
        System.out.println("name:" + model.getUsername() + "password" + model.getPassword());

        ActionContext.getContext().getSession().put("user",user);
        List<User> userList=userService.findAll();
        ActionContext.getContext().put("userList",userList);
        if (user!=null) {

//            message = "登陆成功";
            this.addActionMessage("登陆成功");
            return "loginSuccess";
        } else {
//            message = "登录失败";
            this.addActionError("登录失败");
            return "loginFail";

        }

    }

    @Override
    public User getModel() {
        return model;
    }
}
